#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_exam1.py
# author:王雯雯
# datetime:2024-12-7
# software: PyCharm

import socket

# 创建UDP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定本地地址和端口
server_address = ('localhost', 9999)
server_socket.bind(server_address)
print('UDP服务器正在监听端口 9999...')

while True:
    # 接收数据，最多接收1024字节，同时获取客户端地址
    data, client_address = server_socket.recvfrom(1024)
    if data:
        print(f'从客户端 {client_address} 接收到消息: {data.decode("utf-8")}')
        # 回复客户端消息
        message = input('请输入回复消息: ')
        server_socket.sendto(message.encode('utf-8'), client_address)
